//
//  SXHAVAudioManager.m
//  WisdomAgriculture
//
//  Created by sxh on 2020/10/2.
//

#import "SXHAVAudioManager.h"
#import <AVFoundation/AVFoundation.h>

@interface SXHAVAudioManager()
<
    AVAudioRecorderDelegate
>
@property (nonatomic, strong) AVAudioRecorder *audioRecorder;//音频录音机

@property (nonatomic, copy) NSString *audioPath;//录音存放目录

@property (nonatomic, copy) AVAudioPlayer *player;//播放器必须是全局的

@end

@implementation SXHAVAudioManager

+ (instancetype)shareInstace {
    static SXHAVAudioManager *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[SXHAVAudioManager alloc] init];
    });
    return shared;
}

#pragma mark - event methods
//开始录音
- (void)startRecordNotice {
    if ([self.audioRecorder isRecording]) {
        [self.audioRecorder stop];
    }
    //删除录音文件
    [self.audioRecorder deleteRecording];
    //创建音频会话对象
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    if (![self.audioRecorder isRecording]) {
        [self.audioRecorder record];
    }
}

//暂停录音
- (void)pauseRecordNotice {
    [self.audioRecorder pause];
}

//停止录音
- (void)stopRecordNotice {
    [self.audioRecorder stop];
}

- (void)playRecordNotice {
    if ([[NSFileManager defaultManager] fileExistsAtPath:self.audioPath]) {
        
        [self.player play];
    }else {
        NSLog(@"文件不存在");
    }
    
}

#pragma mark - 获取录音文件
- (NSMutableDictionary *)getAudioSetting {
    NSMutableDictionary *audioSettings = @{}.mutableCopy;
    //录音格式
    [audioSettings setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    //采样率
    [audioSettings setValue:[NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
    //通道数
    [audioSettings setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
    //线性采样位数
    [audioSettings setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //音频质量,采样质量
    [audioSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
    return audioSettings;
}

#pragma mark - 初始化录音机对象
- (AVAudioRecorder *)audioRecorder {
    if (!_audioRecorder) {
        //获取Document目录
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        self.audioPath = [path stringByAppendingPathComponent:@"111.caf"];
        NSLog(@"文件存放地址%@",self.audioPath);
        NSURL *url = [NSURL URLWithString:self.audioPath];
        //创建录音格式设置,
        NSDictionary *setting = [self getAudioSetting];
        //创建录音机
        NSError *error = nil;
        _audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:setting error:&error];
        //设置代理
        _audioRecorder.delegate = self;
        //监控声波
        _audioRecorder.meteringEnabled = YES;
        if (error) {
            NSLog(@"创建录音机对象发送错误,错误信息：%@",error.localizedDescription);
            return  nil;
        }
    }
    return _audioRecorder;
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    
}

/* if an error occurs while encoding it will be reported to the delegate. */
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error {
    
}

- (AVAudioPlayer *)player{
    if (!_player) {
        NSURL *url = [NSURL fileURLWithPath:self.audioPath];
        NSError *error = nil;
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        NSLog(@"%f",_player.data.length/1024.0);
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        [_player prepareToPlay];
    }
    return _player;
}

@end
